package me.znext.learn.android;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import me.znext.learn.android.db.UserDAO;

import java.util.HashMap;

public class SignInActivity extends AppCompatActivity {
  private Storage storage = Storage.getStorage();
  private UserDAO userDAO;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
    this.setTitle("登录");
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final EditText unameEdit = (EditText) findViewById(R.id.unameEdit);
    final EditText pwEdit = (EditText) findViewById(R.id.pwEdit);

    Button signInBtn = (Button) findViewById(R.id.signInBtn);
    assert signInBtn != null;
    signInBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        assert pwEdit != null;
        assert unameEdit != null;
        signIn(String.valueOf(unameEdit.getText()), String.valueOf(pwEdit.getText()));
      }
    });

    Button signUpBtn = (Button) findViewById(R.id.signUpBtn);
    assert signUpBtn != null;
    signUpBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        gotoSignUp();
      }
    });

    userDAO = new UserDAO(this);
  }

  @SuppressWarnings("Duplicates")
  private void signIn(String uname, String pw) {
    if (userDAO.signIn(uname, pw)) {
      Intent intent = new Intent();
      intent.setClass(SignInActivity.this, CourseSchedule.class);
      HashMap<String, String> profile = userDAO.getProfile(uname);
      profile.put("uname", uname);
      profile.put("pw", pw);
      System.out.println(profile);
      storage.initProfile(profile);
      startActivity(intent);
      finish();
    } else {
      Notice.alert(this, "错误!", "密码输入错误，请重新输入");
    }
  }

  private void gotoSignUp() {
    Intent intent = new Intent();
    intent.setClass(SignInActivity.this, SignupActivity.class);
    startActivity(intent);
  }
}
